<?php

namespace App\Admin\Controllers\User;

use App\Admin\Actions\Extensions\ImportRobotUserButton;
use App\Admin\Actions\Extensions\UserNoticeButton;
use App\Admin\Actions\Grid\User\UserBanAndMuteAction;
use App\Admin\Actions\Grid\User\UserGenderManAction;
use App\Admin\Actions\Grid\User\UserGenderWomanAction;
use App\Admin\Actions\Grid\User\UserCoinAction;
use App\Admin\Actions\Grid\User\UserFinancialAction;
use App\Admin\Actions\Grid\User\UserJewelryAction;
use App\Admin\Actions\Grid\User\UserMemberAction;
use App\Admin\Actions\Grid\User\UserPaycodeUpdateAction;
use App\Admin\Actions\Grid\User\UserRealNameAction;
use App\Admin\Actions\Grid\User\UserShareAction;
use App\Admin\Metrics\Users\AuthUsers;
use App\Admin\Repositories\User\WxUser;
use App\Jobs\UpdateUserInfoJob;
use App\Models\User\WxUserOnline;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Admin\Metrics\Users\TotalUsers;
use App\Admin\Metrics\Users\VipUsers;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class WxUserController extends AdminController
{

    public function users(Request $request)
    {
        $q = $request->get('q');
        global $__MINI_GLOBAL_TENANT_ID__;
        if($__MINI_GLOBAL_TENANT_ID__ > 0){
            return \App\Models\User\WxUser::where('tenant_id', $__MINI_GLOBAL_TENANT_ID__)->where('user_name', 'like', "%$q%")->where(
                function ($query) use ($q){
                    $query->orWhere('id', (int)$q);
                }
            )->paginate(null, ['id', 'user_name as text']);
        }
        return \App\Models\User\WxUser::where('user_name', 'like', "%$q%")->orWhere('id', (int)$q)->paginate(null, ['id', 'user_name as text']);
    }

    public function index(Content $content)
    {
        return $content
            ->header('用户')
            ->description('全部用户')
            ->body(function (Row $row) {
                $row->column(4,new TotalUsers());
                $row->column(4,new AuthUsers());
                $row->column(4,new VipUsers());
            })
            ->body($this->grid());
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $ip_show = Settings::get('app_ip_user_show', 3);

        return Grid::make(new WxUser(), function (Grid $grid) use ($ip_show){
            $grid->simplePaginate();
            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $grid->model()->where('tenant_id', '=', $__MINI_GLOBAL_TENANT_ID__);
            }
            $grid->quickSearch(['id', 'user_name', 'phone', 'email', 'weixin_openid', 'weixin_unionid', 'weixin_app_openid', 'weixin_mp_openid', 'weixin_web_openid', 'weixin_shop_openid'])->placeholder('搜索与用户id，用户名，手机号，邮箱...')->width(35);
            $grid->model()->orderBy('id','desc');
            $grid->showColumnSelector();
            $grid->column('id')->sortable();
            $grid->column('user_name');
            $grid->column('user_avatar')->image('',50);
//            $grid->column('user_background_maps')->image('',50);
//            $grid->column('user_background_maps');
//            $grid->column('user_introduce');
//            $grid->column('user_birthday');
//            $grid->column('user_mobile');
//            $grid->column('weixin_name')->explode()->label();
//            $grid->column('weixin_openid');
            $grid->column('a','其他')->display('更多内容')->modal('详情',function ($res){
                $user = $this;
                $user->origin_phone = _get_origin_attribute('wx_user', [['id', '=', $user->id]], 'phone');
                $user->online = WxUserOnline::where('user_id', $user->id)->first();
                return view('admin/user/info',compact('user'));
            });
//            $grid->column('country');
//            $grid->column('province');
//            $grid->column('city');
//            $grid->column('others')->display(function () {
//                return '认证:'. $this->is_authentication .'<br/>'.
//                       '会员' . $this->is_member.'<br/>'.
//                       '官方' . $this->is_official ? '是':'否';
//            });
            $grid->column('gender')->using([0 => '未知',1 => '男',2 => '女'])->label([
                0 => 'default',
                1 => '#1E9FFF',
                2 => '#FF69B4'
            ])->sortable();
//            $grid->column('authentication_id');
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $grid->column('is_official')->display(function ($v) use ($__MINI_GLOBAL_TENANT_ID__){
                    if(get_user_meta($this->id, 'tenant_id_'.$__MINI_GLOBAL_TENANT_ID__, 'n') == 1){
                        return true;
                    }else{
                        return false;
                    }
                })->switch();
            }else{
                $grid->column('is_official')->switch()->sortable();
            }

            $grid->column('is_authentication')->switch()->sortable();;
            $grid->column('is_member')->using([0=>'否',1=>'是'])->label([
                0 => 'gray',
                1 => 'primary'
            ])->sortable();


            if($ip_show == 1){
                $grid->column('country')->display(function ($v){
                    return '<span title="'.($this->country.'-'.$this->province.'-'.$this->city.'-'.$this->district).'">'.$v.'</span>';
                });
            }else if($ip_show == 2){
                $grid->column('province')->display(function ($v){
                    return '<span title="'.($this->country.'-'.$this->province.'-'.$this->city.'-'.$this->district).'">'.$v.'</span>';
                });
            }else if($ip_show == 3){
                $grid->column('city')->display(function ($v){
                    return '<span title="'.($this->country.'-'.$this->province.'-'.$this->city.'-'.$this->district).'">'.$v.'</span>';
                });
            }else if($ip_show == 3){
                $grid->column('district')->display(function ($v){
                    return '<span title="'.($this->country.'-'.$this->province.'-'.$this->city.'-'.$this->district).'">'.$v.'</span>';
                });
            }else{
                $grid->column('city')->display(function ($v){
                    return '<span title="'.($this->country.'-'.$this->province.'-'.$this->city.'-'.$this->district).'">'.$v.'</span>';
                });
            }

            $grid->column('user_state')->using([0=>'正常',1=>'用户注销',2=>'管理员封号', 3=>'禁言'])->label([
                0 => 'primary',
                1 => 'red',
                2 =>'gray',
                3 => 'gray'
            ])->sortable();

//            $grid->column('follow_mp_state', '服务号')->using([0=>'未知',1=>'取关',2=>'已关'])->label([
//                0 => 'gray',
//                1 => 'gray',
//                2 =>'primary'
//            ]);
//            $grid->column('push_client_id', '推送cid');

            $grid->column('who')->display(function ($v){
                if($v > 0){
                    return '<a href="'.admin_url('users?id='.$v).'" target="_blank">'.UserUtils::get_cached_user_name($v).'</a>';
                }
                return '';
            })->sortable();


            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $grid->column('invite_benefit')->display(function ($v){
                    if($v == -1){
                        return '';
                    }
                    return $v;
                })->editable()->sortable();
                $grid->column('invite_benefit_layer')->select([1=>'普通用户', 2=>'推广专员', 3=>'合伙人']);
            }



            $grid->column('invite_count')->display(function ($v){
                return $v > 0 ?  $v.'人' : 0;
            })->modal('邀请列表',function ($res){
                $user_list = \App\Models\User\WxUser::where('who', $this->id)->where('user_state', 0)->orderBy('created_at', 'desc')->get()->toArray();
                return view('admin/user/invite',compact('user_list'));
            });

            $grid->column('created_at','注册于')->sortable()->display(function ($v){
                if($v){
                    return format_datetime($v->timestamp, 2);
                }
                return  '未知';
            });
            $grid->column('online', '最后在线')->display(function ($v){
                return UserUtils::get_user_online_time($this->id, true);
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('user_name');
                $filter->equal('gender')->select([0 => '未知',1 => '男',2 => '女']);
                $filter->equal('is_official')->select([0=>'否',1=>'是']);
                $filter->equal('is_robot')->select([0=>'普通用户', 1=>'待绑定机器人', 2=>'已绑定机器人']);
                $filter->equal('who');
                $filter->equal('user_state')->select([0=>'正常',1 => '用户注销', 2 => '管理员封号', 3 => '禁言']);
            });

//            $grid->disableBatchDelete();
//            $grid->disableDeleteButton();
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $grid->disableCreateButton();
                $grid->disableDeleteButton();
                $grid->disableBatchDelete();
            }

            $grid->batchActions(function ($batch) {
                $batch->add(new UserGenderManAction());
                $batch->add(new UserGenderWomanAction());
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ === 0){
                    $actions->append((new UserPaycodeUpdateAction())->setKey($this->id));
                    $actions->append((new UserMemberAction())->setKey($this->id));
                    $actions->append((new UserCoinAction())->setKey($this->id));
                    $actions->append((new UserFinancialAction())->setKey($this->id));
                    $actions->append((new UserRealNameAction())->setKey($this->id));
                }
                $actions->append((new UserJewelryAction())->setKey($this->id));
                $actions->append((new UserBanAndMuteAction())->setKey($this->id));
                $actions->append((new UserShareAction())->setKey($this->id));
            });


            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $grid->tools([
                    new UserNoticeButton(),
                    new ImportRobotUserButton(),
                ]);
            }

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxUser(), function (Show $show) {
            global $__MINI_GLOBAL_TENANT_ID__;
            $show->field('id');
            $show->field('user_name');
            $show->field('user_avatar');
            $show->field('user_background_maps')->image();
            $show->field('user_introduce');
            $show->field('user_birthday');
            $show->field('user_mobile');
            $show->field('weixin_name');
            $show->field('weixin_openid');
            $show->field('weixin_unionid');
            $show->field('weixin_mp_openid');
            $show->field('weixin_app_openid');
            $show->field('weixin_web_openid');
            $show->field('weixin_shop_openid');
            $show->field('phone');
            $show->field('real_name');
            $show->field('real_id_card');
            $show->field('country_code');
            $show->field('email');
            $show->field('country');
            $show->field('province');
            $show->field('city');
            $show->field('authentication_id');
            $show->field('is_authentication');
            $show->field('is_member');
            $show->field('is_official');
            $show->field('who');
            $show->field('invite_benefit');
            $show->field('invite_benefit_layer');
            $show->field('user_state');
            $show->field('shop_id');
            $show->field('push_client_id');
            $show->field('is_robot');
            $show->field('black_reason');
            $show->field('created_at');
            $show->field('updated_at');
            $show->disableDeleteButton();

            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $show->disableEditButton();
            }

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        global $__MINI_GLOBAL_REQUEST_ENV__;
        $__MINI_GLOBAL_REQUEST_ENV__ = 'api';
        return Form::make(new WxUser(), function (Form $form) {
            $uid = $form->model()->id;
            $tenant_id = $form->model()->tenant_id;

            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                if(get_user_meta($uid, 'tenant_id_'.$__MINI_GLOBAL_TENANT_ID__, 'n') == 1){
                    $form->model()->is_official = 1;
                }else{
                    $form->model()->is_official = 0;
                }
            }


            $old_user_name = $form->model()->user_name;
            $old_user_avatar = $form->model()->user_avatar;
            $old_user_state = $form->model()->user_state;


            $form->display('id');
            $form->text('user_name');
            $form->image('user_avatar')->url('files/uploads')->uniqueName()->autoUpload()->default(Settings::get('img_default_avatar', ''));
            $form->image('user_background_maps')->url('files/uploads')->uniqueName()->autoUpload()->default(Settings::get('user_background_maps', ''));
            $form->radio('is_authentication')->options([0=>'否',1=>'是'])->default(0);
            $form->radio('is_official')->options([0=>'否',1=>'是'])->default(0);
//            $form->radio('user_state')->options([0=>'正常',1=>'用户注销',2=>'管理员封号', 3=>'禁言']);
//            $form->text('black_reason');

            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $form->select('who')->options(function ($id) {
                    if($id){
                        $user = \App\Models\User\WxUser::find($id);
                        if ($user) {
                            return [$user->id => $user->user_name];
                        }
                    }
                    return null;
                })->ajax('select/users');

                $form->decimal('invite_benefit')->help('-1代表默认同步 [<a href="'.admin_url('invite_benefit/config').'" target="_blank">邀请裂变-配置</a>]中的即时邀请收益，但这里的优先级更高，比如你配置为0.5，则该用户邀请每人获益0.5元');
                $form->select('invite_benefit_layer')->options([1=>'普通用户', 2=>'推广专员', 3=>'合伙人'])->default(1);
            }


            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $form->text('tenant_id', '本站分应用id')->help('忽略这个配置')->default($__MINI_GLOBAL_TENANT_ID__);
            }

            $form->saving(function (Form $form) use ($uid, $tenant_id){

                if(!_empty_($form->input('user_name'))){
                    $form->user_name = str_replace([' 💙🤖', ' 💗🤖', ' 🤖'], '', $form->input('user_name'));
                    if(\App\Models\User\WxUser::where('id', '<>', $uid)->where('user_name', $form->input('user_name'))->exists()){
                        return $form->response()->error('该用户名已存在，请换个名称');
                    }
                }

                global $__MINI_GLOBAL_TENANT_ID__;
                if($form->isEditing()){
                    if($__MINI_GLOBAL_TENANT_ID__ > 0){
                        if($tenant_id != $__MINI_GLOBAL_TENANT_ID__){
                            return $form->response()->warning('分站不能修改其他分站的用户信息');
                        }
                    }
                }else if($form->isCreating()){
                    $form->tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                }

                if($__MINI_GLOBAL_TENANT_ID__ === 0){
                    if(_empty_($form->input('who'))){
                        $form->who = 0;
                    }
                    if(_empty_($form->input('invite_benefit')) || $form->input('invite_benefit') < 0){
                        $form->invite_benefit = -1;
                    }else{
                        $form->invite_benefit = round($form->input('invite_benefit'), 2);
                    }
                }else{
                    $form->deleteInput('who');
                    $form->deleteInput('invite_benefit');
                    $form->deleteInput('invite_benefit_layer');
                }


                $form->weixin_openid = null;
                $form->weixin_shop_openid = null;
                if(!_empty_($form->is_official, true)){
                    if($__MINI_GLOBAL_TENANT_ID__ > 0){
                        if($form->is_official){
                            update_user_meta($uid, 'tenant_id_'.$__MINI_GLOBAL_TENANT_ID__, 1, 'n');
                        }else{
                            update_user_meta($uid, 'tenant_id_'.$__MINI_GLOBAL_TENANT_ID__, null, 'n');
                        }
                        $form->deleteInput('is_official');
                    }
                }

            });


            $form->saved(function (Form $form) use ($old_user_name, $old_user_avatar, $uid, $old_user_state){
                $data = $form->updates();
                if(isset($data['user_name']) && ($old_user_name != $data['user_name'] || $old_user_avatar != $data['user_avatar'])){
                    UpdateUserInfoJob::dispatch($uid);
                }
                Cache::forget('get:cached:user:'.$uid);
                GatewayUtils::success(GatewayUtils::uid2client_id($uid), 12);
//                if($old_user_state == 2 && $data['user_state'] != 2){
//                    update_user_meta($uid, 'sql_injection_times', 0, 'n');
//                }
                $is_official = \App\Models\User\WxUser::where('is_official', 1)->pluck('id')->toArray();
                if($is_official){
                    _update_env([
                        'APP_ADMIN_USER_ID' => implode(',', $is_official),
                    ], [], 1);
                }else{
                    _update_env([
                        'APP_ADMIN_USER_ID' => '',
                    ], [], 1);
                }
            });

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    return $form->response()->error('权限不足，不可以删除其他分站对象');
                }
            });

        });
    }
}
